import clr

clr.AddReference("Mithril.Client, Version=1.0.0.0, Culture=neutral")
clr.AddReference("System.Json, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")

from System import Environment, Uri, UriKind
from System.Json import JsonObject
from System.Net import WebClient
from System.Text import StringBuilder
from System.Windows import Application
from System.Windows.Controls import UserControl, TextBlock, TextBox
from Mithril.Client import MithrilClient

class App:
    def __init__(self):
        self.scene = UserControl()    
        Application.Current.LoadComponent(self.scene, 'app.xaml')
        Application.Current.RootVisual = self.scene
        
        self.scroll_log = self._getelement("scroll_log")
               
        self.chat_button = self._getelement("chat_button")
        self.chat_button.Click += self.handle_chat_button_click
        
        self.chat_text = self._getelement("chat_text")
        
        self.account_key = Application.Current.InitParams["account_key"]
        self.chat_service_url = Application.Current.InitParams["chat_service_url"]
        
        self.mithril_service_url = Application.Current.InitParams["mithril_service_url"]        
        self.mithril = MithrilClient(self.mithril_service_url)
        self.mithril.ConnectCompleted += self.handle_mithril_ConnectCompleted
        self.mithril.SignalRecieved += self.handle_mithril_SignalRecieved
        
        self.buffer = StringBuilder()
        
        self.room_key = None
                
    def handle_mithril_ConnectCompleted(self, sender, args):
        pass
    
    def handle_mithril_SignalRecieved(self, sender, args):
        pass

    def handle_chat_button_click (self, sender, args):
        text = self.chat_text.Text
        if text[0] == '/':
            values = text[1:].split()
            getattr(self, 'command_' + values[0])(*values[1:])
            return

    def command_create(self, channel_name):
        client = WebClient()
        client.BaseAddress = self.chat_service_url
        client.DownloadStringCompleted += self.handler_Create_DownloadStringCompleted
        client.DownloadStringAsync(Uri("create?account=%s&name=%s" % (self.account_key, channel_name), UriKind.Relative));
        
    def handler_Create_DownloadStringCompleted(self, sender, args):
        if not args.Error is None:
            self.append_text(args.Error.InnerException.ToString())
                        
        result = JsonObject.Parse(args.Result)
        self.room_key = result["room_key"]
        
        self.append_text(self.room_key)
                
    def append_text(self, text):
        if self.scroll_log.CheckAccess():
            # buffer the message to the chat buffer.
            self.buffer.Append(text).Append(Environment.NewLine)

            # Re-post the contents of the chat buffer to the chat text and scroll to
            # the bottom.
            self.scroll_log.Content = self.buffer.ToString()
            self.scroll_log.ScrollToVerticalOffset(self.scroll_log.ScrollableHeight)
        else:
            self.scroll_log.Dispatcher.BeginInvoke(self.AppendText, text)

    def _getelement(self, id):
        return self.scene.FindName(id)
    		 
App()